package com.itheima.web.service;

import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //根据username查询数据库中的user信息
        User user = userService.findByUsername(username);
        //判断查询到的user是否为空 为空则数据库中没用当前用户名的user
        if (user == null){
            return null;
        }
        //
        List<GrantedAuthority> list = new ArrayList<>();

        //动态位用户授权
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {

            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions){
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        org.springframework.security.core.userdetails.User security
                = new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
        return security;
    }
}